<template>
	<div id="roleIndex">
		<el-row>
			<!-- 表格查询条件 -->
			<el-col :span="24">
				<el-form :inline="true" ref="stationForm" :model="queryForm">
					<el-form-item><el-input v-model="queryForm.name" placeholder="角色名称/编号"></el-input></el-form-item>
					<el-form-item>
						<el-button type="primary" icon="el-icon-search" @click="getTableDatas()">查询</el-button>
						<el-button @click="resetQueryForm" icon="el-icon-refresh-right">重置</el-button>
					</el-form-item>
				</el-form>
			</el-col>
		</el-row>
		<el-row>
			<!-- 数据表格 -->
			<el-col :span="24">
				<el-row>
					<el-col :span="24">
						<el-button
							type="primary"
							icon="el-icon-plus"
							@click="
								dialog.isEdit = false;
								dialog.saveOrEditDiv = true;
							"
						>
							新增角色
						</el-button>
						<el-popconfirm title="这是一段内容确定删除吗？" @confirm="moreDeletes">
							<el-button slot="reference" type="danger" icon="el-icon-delete">批量删除</el-button>
						</el-popconfirm>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-table :data="tableData" border style="width: 100%" @selection-change="tableDataSelected">
							<el-table-column type="selection" width="55"></el-table-column>
							<el-table-column prop="code" label="编号" align="center"></el-table-column>
							<el-table-column prop="name" label="角色名称" align="center"></el-table-column>
							<el-table-column prop="insertTime" label="创建时间" align="center" :sortable="true"></el-table-column>
							<el-table-column fixed="right" label="操作" align="center" width="220">
								<template slot-scope="scope">
									<el-button @click="rowShow(scope.row)" size="small" icon="el-icon-search" circle title="查看"></el-button>
									<el-button @click="rowEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle title="编辑"></el-button>
									<el-button @click="rowDelete(scope.row)" type="danger" icon="el-icon-delete" size="small" circle title="删除"></el-button>
									<el-dropdown>
										<span class="el-dropdown-link"><i class="el-icon-arrow-down el-icon--right"></i></span>
										<el-dropdown-menu slot="dropdown">
											<el-dropdown-item><span @click="rowMenuRole(scope.row)">菜单权限</span></el-dropdown-item>
											<el-dropdown-item><span @click="rowUserRole(scope.row)">授权用户</span></el-dropdown-item>
										</el-dropdown-menu>
									</el-dropdown>
								</template>
							</el-table-column>
						</el-table>
						<el-pagination
							@size-change="tableSizeChange"
							@current-change="tableCurrentChange"
							:current-page="pageData.page"
							:page-sizes="[10, 20, 40, 100]"
							:page-size="pageData.limit"
							layout="total, sizes, prev, pager, next, jumper"
							:total="pageData.total"
						></el-pagination>
					</el-col>
				</el-row>
			</el-col>
		</el-row>

		<!-- 添加或修改-业务弹窗 -->
		<el-dialog
			:title="dialog.isEdit == true ? '编辑角色' : '新增角色'"
			:visible.sync="dialog.saveOrEditDiv"
			width="30%"
			:show-close="false"
			:destroy-on-close="true"
			:close-on-click-modal="false"
		>
			<el-form ref="saveOrEditDataForm" :rules="saveOrEditDataFormRules" :model="saveOrEditData" label-width="80px">
				<el-form-item label="角色编号" prop="code">
					<el-input show-word-limit v-model="saveOrEditData.code" placeholder="请输入角色编号" maxlength="10"></el-input>
				</el-form-item>
				<el-form-item label="角色名称" prop="name">
					<el-input show-word-limit v-model="saveOrEditData.name" placeholder="请输入角色名称" maxlength="10"></el-input>
				</el-form-item>
				<el-form-item label="备注" prop="comment">
					<el-input
						show-word-limit
						maxlength="150"
						type="textarea"
						:autosize="{ minRows: 2, maxRows: 4 }"
						placeholder="如需备注输入描述"
						v-model="saveOrEditData.comment"
					></el-input>
				</el-form-item>
				<!-- 按钮组 -->
				<el-form-item>
					<el-button type="primary" @click="submitSaveOrEdit" :loading="formLoading">{{ dialog.isEdit == false ? '保存' : '确认修改' }}</el-button>
					<el-button
						@click="
							dialog.saveOrEditDiv = false;
							resetAddOrEditOrShowForm();
						"
					>
						取消
					</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<!-- 添加或修改-业务弹窗 -->
		<el-dialog title="角色详情" :visible.sync="dialog.showDiv" width="50%" :show-close="false" :destroy-on-close="true" :close-on-click-modal="false">
			<el-descriptions class="margin-top" :title="showData.name + '角色信息'" :column="3" border>
				<template slot="extra">
					<el-button
						size="small"
						@click="
							dialog.showDiv = false;
							resetAddOrEditOrShowForm();
						"
					>
						关闭
					</el-button>
				</template>
				<el-descriptions-item>
					<template slot="label">
						<i class="el-icon-user"></i>
						角色编号
					</template>
					{{ showData.code }}
				</el-descriptions-item>
				<el-descriptions-item :span="2">
					<template slot="label">
						<i class="el-icon-user"></i>
						角色名称
					</template>
					{{ showData.name }}
				</el-descriptions-item>
				<el-descriptions-item :span="3">
					<template slot="label">
						<i class="el-icon-chat-dot-square"></i>
						备注
					</template>
					{{ showData.comment }}
				</el-descriptions-item>
			</el-descriptions>
		</el-dialog>

		<!-- 菜单权限-抽屉 -->
		<el-drawer
			title="菜单权限"
			:visible.sync="dialog.menuRoles"
			direction="rtl"
			:show-close="false"
			:destroy-on-close="true"
			:close-on-press-escape="false"
			:wrapperClosable="false"
		>
			<div class="treeDiv1">
				<el-tree
					ref="menuRoleTree"
					:data="nowRowMenuTreeDatas"
					show-checkbox
					node-key="menuID"
					:default-checked-keys="nowRowRoleMenuDatas"
					:props="{ children: 'children', label: 'name' }"
					:default-expand-all="true"
					:check-strictly="true"
				></el-tree>
			</div>
			<div class="treeDiv2">
				<el-button type="primary" @click="submitSaveMenuRoles" :loading="formLoading">保存权限</el-button>
				<el-button
					@click="
						dialog.menuRoles = false;
						resetAddOrEditOrShowForm();
					"
				>
					取消
				</el-button>
			</div>
		</el-drawer>

		<!-- 用户授权-抽屉 -->
		<el-drawer
			title="授权用户"
			:visible.sync="dialog.userRoles"
			direction="rtl"
			:show-close="false"
			:destroy-on-close="true"
			:close-on-press-escape="false"
			:wrapperClosable="false"
			size="80%"
		>
			<div class="treeDiv1">
				<el-row>
					<!-- 表格查询条件 -->
					<el-col :span="24">
						<el-form :inline="true" ref="stationForm" :model="userRoles_queryForm">
							<el-form-item><el-input v-model="userRoles_queryForm.userName" placeholder="用户名称/编号"></el-input></el-form-item>
							<el-form-item>
								<el-button type="primary" icon="el-icon-search" @click="getRoleUserDatas()">查询</el-button>
								<el-button @click="resetUserRolesQueryForm()" icon="el-icon-refresh-right">重置</el-button>
							</el-form-item>
						</el-form>
					</el-col>
				</el-row>
				<el-row>
					<!-- 数据表格 -->
					<el-col :span="24">
						<el-row>
							<el-col :span="24"><el-button type="primary" icon="el-icon-plus" @click="toAddRoleUser()">添加授权用户</el-button></el-col>
						</el-row>
					</el-col>
				</el-row>
				<el-table :data="userRoles_tableData" border style="width: 100%" @selection-change="userRoles_tableDataSelected">
					<el-table-column type="selection" width="55"></el-table-column>
					<el-table-column prop="userName" label="用户名" align="center"></el-table-column>
					<el-table-column fixed="right" label="操作" align="center" width="220">
						<template slot-scope="scope">
							<el-button @click="roleUserRowDelete(scope.row)" type="danger" icon="el-icon-delete" size="small" circle title="移除授权"></el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination
					@size-change="userRoles_tableDataSizeChange"
					@current-change="userRoles_tableDataCurrentChange"
					:current-page="userRoles_pageData.page"
					:page-sizes="[10, 20, 40, 100]"
					:page-size="userRoles_pageData.limit"
					layout="total, sizes, prev, pager, next, jumper"
					:total="userRoles_pageData.total"
				></el-pagination>
			</div>
			<div class="treeDiv2">
				<el-button
					@click="
						dialog.userRoles = false;
						resetAddOrEditOrShowForm();
					"
				>
					取消
				</el-button>
			</div>
		</el-drawer>

		<!-- 选择添加授权的用户弹窗 -->
		<el-dialog title="选择用户授权" :visible.sync="dialog.addRoleUser" width="50%" :show-close="false" :destroy-on-close="true" :close-on-click-modal="false">
			<el-row>
				<!-- 表格查询条件 -->
				<el-col :span="24">
					<el-form :inline="true" ref="stationForm" :model="userRoles_user_queryForm">
						<el-form-item><el-input v-model="userRoles_user_queryForm.userName" placeholder="用户名称/编号"></el-input></el-form-item>
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" @click="getAllUserData()()">查询</el-button>
							<el-button @click="resetUserRolesAddUserQueryForm()" icon="el-icon-refresh-right">重置</el-button>
						</el-form-item>
					</el-form>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					已选择用户：
					<el-tag
					  v-for="tag in toSaveUserRoleData.userList"
					  :key="tag.userName"
					  closable
					  @close="tagRemoveUser(tag)">
					  {{tag.userName}}
					</el-tag>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-table row-key="accountID" ref="userRoles_user_table" :data="userRoles_user_tableData" border style="width: 100%" @selection-change="userRoles_tableDataSelected">
						<el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
						<el-table-column prop="userName" label="用户名" align="center"></el-table-column>
					</el-table>
					<el-pagination
						@size-change="userRoles_user_tableDataSizeChange"
						@current-change="userRoles_user_tableDataCurrentChange"
						:current-page="userRoles_user_pageData.page"
						:page-sizes="[2,10, 20, 40, 100]"
						:page-size="userRoles_user_pageData.limit"
						layout="total, sizes, prev, pager, next, jumper"
						:total="userRoles_user_pageData.total"
					></el-pagination>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="24">
					<el-button type="primary" @click="submitRoleUserAdd" :loading="formLoading">确定授权</el-button>
					<el-button
						@click="
							dialog.addRoleUser = false;
							resetUserRolesAddUserQueryForm();
						"
					>
						取消
					</el-button>
				</el-col>
			</el-row>
		</el-dialog>
	</div>
</template>

<script>
import * as roleAPI from '@/api/role.js';
import * as menuAPI from '@/api/menu.js';
import * as accountAPI from '@/api/account.js';
export default {
	name: 'roleIndex',
	data() {
		return {
			//查询表单数据
			queryForm: {
				name: null
			},
			userRoles_queryForm: {
				userName: null
			},
			userRoles_user_queryForm: {
				userName: null
			},
			//表格数据
			tableData: [],
			//主表-分页数据
			pageData: {
				page: 1,
				limit: 10,
				total: 0
			},
			//角色授权用户-表格数据
			userRoles_tableData: [],
			//角色授权用户-分页数据
			userRoles_pageData: {
				page: 1,
				limit: 10,
				total: 0
			},
			//角色授权-添加用户表格-分页
			userRoles_user_pageData: {
				page: 1,
				limit: 2,
				total: 0
			},
			//角色授权-添加用户表格-数据
			userRoles_user_tableData: [],
			//当前表格复选数据
			nowTableSelected: [],
			//弹窗状态
			dialog: {
				isEdit: false,
				saveOrEditDiv: false,
				showDiv: false,
				addRoleUser: false,
				menuRoles: false,
				userRoles: false
			},
			//添加或编辑表单数据
			saveOrEditData: {
				roleID: null,
				comment: null,
				name: null,
				code: null
			},
			//添加编辑表单-检验
			saveOrEditDataFormRules: {
				code: { required: true, message: '请输入角色编号', trigger: 'blur' },
				name: { required: true, message: '请输入角色名称', trigger: 'blur' }
			},
			//展示表单数据
			showData: {
				roleID: null,
				comment: null,
				name: null,
				code: null
			},
			//表单加载值
			formLoading: false,
			//当前行的菜单数据信息
			nowRowMenuTreeDatas: [],
			//当前行角色的菜单权限数据
			nowRowRoleMenuDatas: [],
			//保存菜单权限修改数据
			toSaveMenuRoleData: {
				roleID: null,
				menuIDs: []
			},
			//保存用户权限修改数据
			toSaveUserRoleData: {
				roleID: null,
				userList: []
			}
		};
	},
	computed: {},
	mounted() {
		this.getTableDatas();
	},
	methods: {
		//查询表格数据
		getTableDatas() {
			let _this = this;
                roleAPI.pages(_this.queryForm,_this.pageData)
				.then(function(response) {
					console.log(response);
					if (response.code == '0000') {
						_this.tableData = response.data.pageData;
						_this.pageData.total = response.data.total;
					} 
				});
		},
		//重置查询条件表单
		resetQueryForm() {
			this.queryForm = {
				name: null
			};
			this.getTableDatas();
		},
		//查询角色授权用户表格数据
		async getRoleUserDatas() {
			let _this = this;
                roleAPI.roleUserpages(_this.userRoles_queryForm,_this.userRoles_pageData,_this.toSaveUserRoleData.roleID)
				.then(function(response) {
					console.log(response);
					if (response.code == '0000') {
						_this.userRoles_tableData = response.data.pageData;
						_this.userRoles_pageData.total = response.data.total;
					} 
				});
		},
		//查询所有的用户信息
		getAllUserData() {
			let _this = this;
            _this.userRoles_user_pageData.size = _this.userRoles_user_pageData.limit;
                accountAPI.page(_this.userRoles_user_queryForm,_this.userRoles_user_pageData)
				.then(function(response) {
					if (response.code == '0000') {

						_this.userRoles_user_tableData = response.data.rows;
						_this.userRoles_user_pageData.total = response.data.total;
					}
				});
		},
		//重置-授权用户查询条件表单
		resetUserRolesQueryForm() {
			this.userRoles_queryForm = {
				userName: null
			};
			this.getRoleUserDatas();
		},
		//重置-添加授权用户查询条件表单
		resetUserRolesAddUserQueryForm() {
			this.userRoles_user_queryForm = {
				userName: null
			};
			this.toSaveUserRoleData.userList = [];
			this.getAllUserData();
		},
		//重置添加、编辑、展示表单
		resetAddOrEditOrShowForm() {
			this.showData = {
				roleID: null,
				comment: null,
				name: null,
				code: null
			};
			this.saveOrEditData = {
				roleID: null,
				comment: null,
				name: null,
				code: null
			};
			this.nowRowMenuTreeDatas = [];
			this.nowRowRoleMenuDatas = [];
			this.toSaveMenuRoleData.roleID = null;
			this.toSaveMenuRoleData.menuIDs = [];
			this.toSaveUserRoleData.roleID = null;
			this.toSaveUserRoleData.userList = [];
			this.userRoles_queryForm = {
				userName: null
			};
		},
		//提交-添加、编辑表单
		submitSaveOrEdit() {
			let _this = this;
			this.$refs.saveOrEditDataForm.validate(valid => {
				if (valid) {
					this.formLoading = true;
					let _this = this;

                    if(_this.dialog.isEdit == true){ // 编辑
                        roleAPI.updateRole(_this.saveOrEditData)
                            .then(function(res) {
                            if (res.code == '0000') {
                                _this.dialog.saveOrEditDiv = false;
                                _this.resetAddOrEditOrShowForm();
                                _this.formLoading = false;
                                _this.getTableDatas();
                            } else {
                                _this.formLoading = false;
                            }
                        });
                    }else{// 添加
                        roleAPI.addRole(_this.saveOrEditData)
                            .then(function(res) {
                            if (res.code == '0000') {
                                _this.dialog.saveOrEditDiv = false;
                                _this.resetAddOrEditOrShowForm();
                                _this.formLoading = false;
                                _this.getTableDatas();
                            } else {
                                _this.formLoading = false;
                            }
                        });
                    }
				} else {
					return false;
				}
			});
		},
		//提交-删除
		submitDelete(ids) {
			let _this = this;
            roleAPI.deletesRole(ids)
				.then(res => {
					if (res.code == '0000') {
						_this.getTableDatas();
					} 
				});
		},
		//提交-移除授权用户
		submitRoleUserDelete(ids) {
			let _this = this;
            roleAPI.deletesRoleUsers(ids)
				.then(res => {
					if (res.code == '0000') {
						_this.getRoleUserDatas();
					}
				});
		},
		//提交-菜单权限的改变
		submitSaveMenuRoles() {
			let menuIDs = this.$refs.menuRoleTree.getCheckedKeys();
			this.toSaveMenuRoleData.menuIDs = menuIDs;
			let _this = this;
            roleAPI.updateMenuRoles(_this.toSaveMenuRoleData)
                .then(function(res) {
                    if (res.code == '0000') {
                        _this.dialog.menuRoles = false;
                        _this.resetAddOrEditOrShowForm();
                        
                        _this.formLoading = false;
                    } else {
                        _this.formLoading = false;
                    }
                });
		},
		//提交用户授权
		submitRoleUserAdd(){
			if(this.toSaveUserRoleData.userList.length<=0){
				this.$notify.error({
					title: '操作提示',
					message: "请至少选择一个用户进行授权保存操作！"
				});
				return;
			}
			this.formLoading = true;
			let _this = this;
            roleAPI.addRoleUser(_this.toSaveUserRoleData)
                .then(function(res) {
                    if (res.code == '0000') {
                        _this.dialog.addRoleUser = false;
                        _this.resetUserRolesAddUserQueryForm();
                        _this.getRoleUserDatas();
                        _this.formLoading = false;
                    } else {
                        _this.formLoading = false;
                    }
                });
		},
		//分页条目数切换
		tableSizeChange(size) {
			this.pageData.limit = size;
			this.getTableDatas();
		},
		//页码切换
		tableCurrentChange(page) {
			this.pageData.page = page;
			this.getTableDatas();
		},
		//行-查看
		rowShow(data) {
			this.showData = JSON.parse(JSON.stringify(data));
			this.dialog.showDiv = true;
		},
		//行-编辑
		rowEdit(data) {
			this.dialog.saveOrEditDiv = true;
			this.saveOrEditData = JSON.parse(JSON.stringify(data));
			this.dialog.isEdit = true;
		},
		//行-删除
		rowDelete(data) {
			this.$confirm('确定要删除这行数据吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.submitDelete(data.roleID);
			});
		},
		//行-菜单授权
		rowMenuRole(data) {
			this.toSaveMenuRoleData.roleID = data.roleID;
			this.getRoleMenuDataByRoleID(data.roleID);
		},
		//行-用户授权
		rowUserRole(data) {
			this.toSaveUserRoleData.roleID = data.roleID;
			this.getRoleUserDatas();
			this.dialog.userRoles = true;
		},
		//行-授权用户信息表-删除
		roleUserRowDelete(data) {
			this.$confirm('确定要移除用户【' + data.userName + '】的授权吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.submitRoleUserDelete(data.infoID);
			});
		},
		test(){
			this.getMenuDatas();
			this.getRoleMenuDataByRoleID();
		},
		//获取菜单数据
		async getMenuDatas() {
			let _this = this;
            menuAPI.list().then(res => {
				if (res.code == '0000') {
					let treeData = _this.$myUtil.list2TreeData(res.data,"-1", 'menuID');
					_this.nowRowMenuTreeDatas = treeData;
				} 
			});
		},
		//获取当前角色的菜单权限数据
		async getRoleMenuDataByRoleID(roleID) {
			let _this = this;
            roleAPI.getRoleMenuListByRoleID(roleID)
				.then(res => {
					if (res.code == '0000') {
						for (var i in res.data) {
							_this.nowRowRoleMenuDatas.push(res.data[i].menuID);
						}
						
						_this.getMenuDatas(); // 获取所有的菜单数据
						_this.dialog.menuRoles = true;
						_this.toSaveMenuRoleData.roleID = roleID;
					}
				});
		},
		//点击批量删除
		moreDeletes() {
			if (this.nowTableSelected.length <= 0) {
				this.$notify.warning({
					title: '删除提示',
					message: '请至少选择一条数据再删除'
				});
				return;
			}
			let ids = '';

			for (var i in this.nowTableSelected) {
				ids += this.nowTableSelected[i].roleID + ',';
			}

			ids = ids.substring(0, ids.length - 1);

			//调用删除
			this.submitDelete(ids);
		},
		//表格批量选择
		tableDataSelected(data) {
			this.nowTableSelected = data;
		},
		//角色授权用户表格批量选择
		userRoles_tableDataSelected(data) {
			for(var i in data){
				let tempUserID = data[i].accountID;
				let isHave = false;
				for(var c in this.toSaveUserRoleData.userList){
					if(this.toSaveUserRoleData.userList[c].accountID == tempUserID){
						isHave = true;
						break;
					}
				}
				if(!isHave){
					this.toSaveUserRoleData.userList.push(data[i]);
				}
			}
			
		},
		//添加授权用户
		toAddRoleUser() {
			this.getAllUserData();
			this.dialog.addRoleUser = true;
		},
		//已授权用户-分页切换-行数
		userRoles_tableDataSizeChange(data) {
			this.userRoles_pageData.limit = data;
			this.getRoleUserDatas();
		},
		//已授权用户-分页切换-换页
		userRoles_tableDataCurrentChange(data) {
			this.userRoles_pageData.page = data;
			this.getRoleUserDatas();
		},
		//用户列表-分页切换
		userRoles_user_tableDataSizeChange(data) {
			this.userRoles_user_pageData.limit = data;
			this.getAllUserData();
		},
		//用户列表-页码切换
		userRoles_user_tableDataCurrentChange(data) {
			this.userRoles_user_pageData.page = data;
			this.getAllUserData();
		},
		//用户列表-分页切换时让表格选中
		userRoles_user_tableDataChangeToSelect(){
			for(var i in this.toSaveUserRoleData.userList){
				this.$refs.userRoles_user_table.toggleRowSelection(this.toSaveUserRoleData.userList[i]);
			}
			
		},
		//已选择用户tag小标签移除
		tagRemoveUser(data){
			for(var i in this.toSaveUserRoleData.userList){
				
				if(this.toSaveUserRoleData.userList[i].accountID == data.accountID){
					this.$delete(this.toSaveUserRoleData.userList,i);
					break;
				}
			}
		}
	}
};
</script>

<style scoped>
.treeDiv1 {
	width: 100%;
	height: 90%;
	float: left;
	box-sizing: border-box;
	padding: 10px;
}

.treeDiv2 {
	width: 100%;
	height: 10%;
	float: left;
	text-align: center;
}
</style>
